<?php

/**
 * resize image.
 * @package Util
 * @author bartu
 */
class ImageResize {
	protected $sourceImage;
	protected $newImage = object;
	protected $imageType;

	public function __construct($sourceImage, $maxWidth = 800, $maxHeight = 600) {
		$this->sourceImage = $sourceImage;

		$picInfos = getimagesize($this->sourceImage);
		$width    = $picInfos[0];
		$height   = $picInfos[1];

		$typeArray = explode("/", $picInfos["mime"]);
		$this->imageType = $typeArray[1];

		if ($width > $maxWidth & $height <= $maxHeight) {
			$ratio = $maxWidth / $width;
		} elseif ($height > $maxHeight & $width <= $maxWidth) {
			$ratio = $maxHeight / $height;
		} elseif ($width > $maxWidth & $height > $maxHeight) {
			$ratio1 = $maxWidth / $width;
			$ratio2 = $maxHeight / $height;
			$ratio  = ($ratio1 < $ratio2) ? $ratio1 : $ratio2;
		} else {
			$ratio = 1;
		}

		$nWidth  = floor($width * $ratio);
		$nHeight = floor($height * $ratio);

		if ($this->imageType == "jpeg") {
			$origPic = imagecreatefromjpeg($this->sourceImage);
		} elseif ($this->imageType == "png") {
			$origPic = imagecreatefrompng($this->sourceImage);
		}

		$this->newImage = imagecreatetruecolor($nWidth, $nHeight);
		imagecopyresampled($this->newImage, $origPic, 0, 0, 0, 0, $nWidth, $nHeight, $width, $height);
	}

	public function saveTo($name = "", $path = ".") {
		if (empty($name)) {
			throw new Exception("Image name?");
		} elseif(!is_dir($path)) {
			throw new Exception($path . " is not a directory!");
		} else {
			if ($this->imageType == "jpeg") {
				imagejpeg($this->newImage, $path . "/" . $name, 100);
			} elseif ($this->imageType == "png") {
				imagepng($this->newImage, $path . "/" . $name, 100);
			}
		}
	}

}

?>